import React, { useEffect } from 'react'

export default React.forwardRef(
  ({ slots, guides, drawingMode, startPos, onClick }, ref) => {
    useEffect(() => {
      const canvas = ref.current
      const ctx = canvas.getContext('2d')
      ctx.clearRect(0, 0, canvas.width, canvas.height)

      // 绘制网格
      ctx.strokeStyle = '#eee'
      for (let i = 0; i < canvas.width; i += 50) {
        ctx.beginPath()
        ctx.moveTo(i, 0)
        ctx.lineTo(i, canvas.height)
        ctx.stroke()
      }
      for (let j = 0; j < canvas.height; j += 50) {
        ctx.beginPath()
        ctx.moveTo(0, j)
        ctx.lineTo(canvas.width, j)
        ctx.stroke()
      }

      // 绘制车位
      slots.forEach((slot) => {
        ctx.fillStyle = slot.occupied ? '#ff6b6b' : '#51cf66'
        ctx.fillRect(slot.x, slot.y, 60, 30)
        ctx.fillStyle = '#fff'
        ctx.font = '12px Arial'
        ctx.textAlign = 'center'
        ctx.fillText(slot.id, slot.x + 30, slot.y + 18)
      })

      // 绘制引导线
      guides.forEach((guide) => {
        ctx.beginPath()
        ctx.moveTo(guide.start.x, guide.start.y)
        ctx.lineTo(guide.end.x, guide.end.y)
        ctx.strokeStyle = '#ff922b'
        ctx.lineWidth = 3
        ctx.stroke()

        // 绘制箭头
        const angle = Math.atan2(
          guide.end.y - guide.start.y,
          guide.end.x - guide.start.x
        )
        ctx.beginPath()
        ctx.moveTo(guide.end.x, guide.end.y)
        ctx.lineTo(
          guide.end.x - 12 * Math.cos(angle - Math.PI / 6),
          guide.end.y - 12 * Math.sin(angle - Math.PI / 6)
        )
        ctx.lineTo(
          guide.end.x - 12 * Math.cos(angle + Math.PI / 6),
          guide.end.y - 12 * Math.sin(angle + Math.PI / 6)
        )
        ctx.closePath()
        ctx.fillStyle = '#ff922b'
        ctx.fill()
      })

      // 绘制临时引导线
      if (drawingMode) {
        ctx.beginPath()
        ctx.moveTo(startPos.x, startPos.y)
        ctx.lineTo(startPos.x + 1, startPos.y + 1)
        ctx.strokeStyle = '#339af0'
        ctx.lineWidth = 2
        ctx.setLineDash([5, 3])
        ctx.stroke()
        ctx.setLineDash([])
      }
    }, [slots, guides, drawingMode, startPos])

    return (
      <canvas
        ref={ref}
        width={800}
        height={500}
        onClick={onClick}
        style={{
          border: '1px solid #ddd',
          cursor: drawingMode ? 'crosshair' : 'default',
        }}
      />
    )
  }
)
